<!DOCTYPE html>
<html>
<head>
    <title>临时邮箱</title>
    <meta charset="utf-8">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f5f7fa;
        }

        .container {
            max-width: 900px;
            margin: 4rem auto 2rem;
            padding: 0 1rem;
            display: flex;
            flex-direction: column;
            gap: 1.5rem;
        }

        h1 {
            color: #2c3e50;
            font-size: 2rem;
            margin-bottom: 1.5rem;
            text-align: center;
        }

        .email-input-group {
            background: white;
            padding: 1.25rem;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            display: flex;
            gap: 1rem;
            align-items: center;
        }

        #emailInput {
            flex: 1;
            padding: 0.75rem 1rem;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            font-size: 1rem;
            outline: none;
            transition: border-color 0.2s;
        }

        #emailInput:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59,130,246,0.1);
        }

        .button-group {
            display: flex;
            gap: 0.75rem;
            flex-wrap: wrap;
        }

        .button {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 1rem;
        }

        .button-primary {
            background-color: #3b82f6;
            color: white;
        }

        .button-primary:hover {
            background-color: #2563eb;
            transform: translateY(-1px);
        }

        .button-secondary {
            background-color: #f3f4f6;
            color: #374151;
        }

        .button-secondary:hover {
            background-color: #e5e7eb;
            transform: translateY(-1px);
        }

        .button-danger {
            background-color: #ef4444;
            color: white;
        }

        .button-danger:hover {
            background-color: #dc2626;
        }

        #status {
            margin: 1rem 0;
            padding: 0.75rem;
            border-radius: 6px;
            background: white;
            color: #475569;
            font-size: 0.95rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        #lastUpdate {
            color: #64748b;
            font-size: 0.9rem;
            margin-bottom: 1rem;
        }

        .email-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            margin-top: 1.5rem;
            overflow: hidden;
        }

        .email-header {
            background-color: #f8fafc;
            padding: 1.25rem;
            border-bottom: 1px solid #e2e8f0;
        }

        .email-header-item {
            margin: 0.5rem 0;
            color: #475569;
        }

        .tab-buttons {
            padding: 1rem;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            gap: 1rem;
        }

        .tab-button {
            padding: 0.5rem 1rem;
            border: none;
            background: none;
            color: #64748b;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            border-radius: 4px;
        }

        .tab-button:hover {
            background-color: #f1f5f9;
        }

        .tab-button.active {
            color: #3b82f6;
            background-color: #eff6ff;
        }

        .email-content {
            padding: 1.5rem;
            min-height: 300px;
        }

        .email-content iframe {
            width: 100%;
            min-height: 400px;
            border: none;
            background: white;
        }

        .test-email-section {
            margin-top: 2rem;
            text-align: center;
            padding: 1.5rem;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        #testEmailResult {
            margin-top: 1rem;
            padding: 0.75rem;
            border-radius: 4px;
            font-size: 0.95rem;
        }

        .success {
            color: #059669;
            background-color: #ecfdf5;
        }

        .error {
            color: #dc2626;
            background-color: #fef2f2;
        }

        .email-attachments {
            margin-top: 1rem;
            padding: 1rem;
            background-color: #f8fafc;
            border-radius: 6px;
        }

        .attachment-item {
            padding: 0.5rem;
            margin: 0.5rem 0;
            background: white;
            border-radius: 4px;
            border: 1px solid #e2e8f0;
        }

        @media (max-width: 768px) {
            .container {
                margin: 2.5rem auto 1rem;
            }

            .email-input-group {
                flex-direction: column;
            }

            .button {
                width: 100%;
            }

            .email-header {
                padding: 1rem;
            }
        }

        .status-section {
            background: white;
            padding: 1.25rem;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .status-container {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        #status {
            flex: 1;
        }

        #lastUpdate {
            margin: 0;
            min-width: 200px;
        }

        .status-buttons {
            display: flex;
            gap: 0.75rem;
            margin-left: auto;
        }

        @media (max-width: 768px) {
            .status-container {
                flex-direction: column;
                align-items: stretch;
            }

            .status-buttons {
                margin-left: 0;
                width: 100%;
            }

            .status-buttons .button {
                flex: 1;
            }
        }

        .action-buttons-section {
            background: white;
            padding: 1.25rem;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            margin-top: 1.5rem;
        }

        .action-buttons-container {
            display: flex;
            gap: 1rem;
            justify-content: center;
        }

        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }

        #toggleMonitor.monitoring {
            background-color: #ef4444;
        }

        @media (max-width: 768px) {
            .email-input-group,
            .action-buttons-container {
                flex-direction: column;
            }

            .button {
                width: 100%;
            }
        }

        /* 改状态容器样式 */
        .status-container {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        /* 添加图标按钮样式 */
        .button-icon {
            width: 32px;
            height: 32px;
            padding: 0;
            border-radius: 50%;
            font-size: 1rem;
            min-width: unset;
            flex-shrink: 0;
        }

        /* 移除监控按钮的动画效果 */
        #toggleMonitor.monitoring {
            background-color: #ef4444;
        }

        /* 确保状态文本占据剩余空间 */
        #status {
            flex: 1;
        }

        /* 响应式布局调整 */
        @media (max-width: 768px) {
            .status-container {
                flex-wrap: wrap;
            }
            
            #status, #lastUpdate {
                flex: 1;
                min-width: 0;
            }
        }

        /* 新增邮箱盒子样式 */
        .email-box {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        /* 修改邮箱输入组样式 */
        .email-input-group {
            padding: 1.25rem;
            display: flex;
            gap: 1rem;
            align-items: center;
            border-bottom: 1px solid #f0f2f5;
            background: none;
            box-shadow: none;
            border-radius: 0;
        }

        /* 修改状态栏样式 */
        .status-section {
            padding: 1.25rem;
            background: none;
            box-shadow: none;
            border-radius: 0;
        }

        /* 修改状态容器样式 */
        .status-container {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        /* 移除状态文本的阴影和背景 */
        #status {
            flex: 1;
            margin: 0;
            padding: 0;
            background: none;
            box-shadow: none;
        }

        /* 修改最后更新时间样式 */
        #lastUpdate {
            color: #64748b;
            font-size: 0.9rem;
            margin: 0;
            white-space: nowrap;
            text-align: right;
        }

        /* 响应式布局调整 */
        @media (max-width: 768px) {
            .email-input-group {
                flex-direction: column;
            }
            
            .status-container {
                flex-wrap: wrap;
            }
            
            #status, #lastUpdate {
                flex: 1;
                min-width: 0;
            }
            
            #lastUpdate {
                text-align: right;
            }
        }

        .test-email-result {
            margin-top: 1rem;
            padding: 0.75rem;
            text-align: center;
            border-radius: 6px;
            font-size: 0.95rem;
        }

        .test-email-result:empty {
            display: none;
        }

        .test-email-result.success {
            color: #059669;
            background-color: #ecfdf5;
        }

        .test-email-result.error {
            color: #dc2626;
            background-color: #fef2f2;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>临时邮箱</h1>
        
        <div class="email-box">
            <div class="email-input-group">
                <input type="text" id="emailInput" placeholder="输入要监控的邮箱地址">
                <button class="button button-secondary" onclick="generateRandomEmail()">
                    🔄 更换邮箱
                </button>
            </div>
            <div class="status-section">
                <div class="status-container">
                    <button id="toggleMonitor" class="button button-icon button-primary" onclick="toggleMonitoring()">
                        ▶
                    </button>
                    <div id="status">状态: 未开始监控</div>
                    <div id="lastUpdate">更新于: -</div>
                </div>
            </div>
        </div>

        <div class="action-buttons-section" style="display: {{#if debug}}block{{else}}none{{/if}}">
            <div class="action-buttons-container">
                <button class="button button-primary" onclick="checkOnce()">
                    📥 立即收信
                </button>
                <button id="sendTestEmail" class="button button-secondary">
                    ✉️ 发送测试邮件
                </button>
            </div>
            <div id="testEmailResult" class="test-email-result"></div>
        </div>

        <div class="email-container" id="emailContainer" style="display: none;">
            <div class="email-header">
                <div class="email-header-item" id="emailSubject"></div>
                <div class="email-header-item" id="emailFrom"></div>
                <div class="email-header-item" id="emailTo"></div>
                <div class="email-header-item" id="emailDate"></div>
            </div>
            <div class="tab-buttons">
                <button class="tab-button active" onclick="switchView('html')">HTML</button>
                <button class="tab-button" onclick="switchView('text')">纯文本</button>
                <button class="tab-button" onclick="switchView('raw')">RAW</button>
            </div>
            <div class="email-content">
                <div id="htmlView" class="content-view active"></div>
                <div id="textView" class="content-view"></div>
                <div id="rawView" class="content-view"></div>
            </div>
        </div>
    </div>

    <script>
        let checkInterval;
        let currentEmail = '';
        const DOMAIN = '{{domain}}';
        let lastUpdateTime = null;
        let lastCheckTimestamp = null;
        let pageLoadTime = Date.now();
        let highFrequencyInterval = 5000; // 5秒
        let lowFrequencyInterval = 60000; // 1分钟
        let highFrequencyDuration = 5 * 60 * 1000; // 5分钟

        // 立即执行邮箱回填
        (function initializeEmail() {
            const emailInput = document.getElementById('emailInput');
            if (emailInput) {  // 确保元素已存在
                const savedEmail = getEmailFromLocalStorage();
                if (savedEmail && validateEmail(savedEmail)) {
                    emailInput.value = savedEmail;
                    // 延迟执行 startChecking，确保其他必要的DOM元素都已加载
                    setTimeout(() => startChecking(), 0);
                } else {
                    setTimeout(() => generateRandomEmail(), 0);
                }
            } else {
                // 如果元素还不存在，等待一小段时间后重试
                setTimeout(initializeEmail, 10);
            }
        })();

        function parseEmail(content) {
            try {
                // 分离邮件头和正文
                const [headers, ...bodyParts] = content.split('\r\n\r\n');
                const body = bodyParts.join('\r\n\r\n');

                // 解邮件头
                const headerMap = {};
                headers.split('\r\n').forEach(line => {
                    const [key, ...values] = line.split(': ');
                    if (key && values.length) {
                        headerMap[key.toLowerCase()] = values.join(': ');
                    }
                });

                // 解码主题（如果是 GB2312 编码）
                let subject = headerMap['subject'] || '无主题';
                if (subject.includes('=?GB2312?B?')) {
                    subject = subject.replace(/=\?GB2312\?B\?(.*?)\?=/g, (match, p1) => {
                        try {
                            return Buffer.from(p1, 'base64').toString('utf8');
                        } catch (e) {
                            return match;
                        }
                    });
                }

                // 检查内容类型和边界
                const contentType = headerMap['content-type'] || '';
                const boundary = contentType.includes('boundary=') 
                    ? contentType.split('boundary=')[1].split(';')[0].replace(/["']/g, '').trim()
                    : null;

                let htmlContent = '';
                let textContent = '';

                if (boundary) {
                    // 处理多部分内容
                    const parts = body.split('--' + boundary).filter(part => part.trim() && !part.includes('--' + boundary + '--'));
                    
                    parts.forEach(part => {
                        const partHeaders = part.split('\r\n\r\n')[0];
                        const partContent = part.split('\r\n\r\n').slice(1).join('\r\n\r\n');
                        
                        const isHtml = partHeaders.toLowerCase().includes('text/html');
                        const isPlain = partHeaders.toLowerCase().includes('text/plain');
                        const encoding = partHeaders.toLowerCase().includes('content-transfer-encoding:') 
                            ? partHeaders.toLowerCase().split('content-transfer-encoding:')[1].split('\r\n')[0].trim()
                            : '';
                        const charset = partHeaders.toLowerCase().includes('charset=')
                            ? partHeaders.toLowerCase().split('charset=')[1].split('"')[1] || partHeaders.toLowerCase().split('charset=')[1].split(';')[0].trim()
                            : 'utf-8';

                        let decodedContent = partContent;

                        // 解码内容
                        if (encoding === 'base64') {
                            try {
                                decodedContent = Buffer.from(partContent.replace(/\r\n/g, ''), 'base64').toString(charset);
                            } catch (e) {
                                console.error('Base64 解码失败:', e);
                            }
                        } else if (encoding === 'quoted-printable') {
                            try {
                                decodedContent = partContent
                                    .replace(/=\r\n/g, '')
                                    .replace(/=([\dA-F]{2})/gi, (_, p1) => String.fromCharCode(parseInt(p1, 16)))
                                    .replace(/=3D/gi, '=');
                            } catch (e) {
                                console.error('Quoted-printable 解码失败:', e);
                            }
                        }

                        if (isHtml) {
                            htmlContent = decodedContent;
                        } else if (isPlain) {
                            textContent = decodedContent;
                        }
                    });
                }

                return {
                    subject: subject,
                    from: headerMap['from'] || '未知发件人',
                    to: headerMap['to'] || '未知收件人',
                    date: headerMap['date'] || '未知时间',
                    html: htmlContent,
                    text: textContent,
                    raw: content
                };
            } catch (error) {
                console.error('解析邮件失败:', error);
                return {
                    subject: '解析失败',
                    from: '',
                    to: '',
                    date: '',
                    html: '',
                    text: '邮件解析失败',
                    raw: content
                };
            }
        }

        function displayEmail(emailData) {
            try {
                const container = document.getElementById('emailContainer');
                console.log('原始邮件数据:', emailData);

                // 如果没有新邮件内容，直接返回
                if (!emailData.content) {
                    return;
                }

                let parsedEmail;
                try {
                    parsedEmail = typeof emailData.content === 'string' ? 
                        JSON.parse(emailData.content) : emailData.content;
                } catch (parseError) {
                    console.error('JSON解析失败:', parseError);
                    parsedEmail = parseEmail(emailData.content);
                }

                // 更新邮件头信息
                document.getElementById('emailSubject').textContent = `主题: ${parsedEmail.subject}`;
                document.getElementById('emailFrom').textContent = `发件人: ${parsedEmail.from}`;
                document.getElementById('emailTo').textContent = `收件人: ${parsedEmail.to}`;
                document.getElementById('emailDate').textContent = `时间: ${new Date(parsedEmail.date).toLocaleString()}`;

                // 根据内容显示或隐藏对应的标签页
                const htmlTab = document.querySelector('[onclick="switchView(\'html\')"]');
                const textTab = document.querySelector('[onclick="switchView(\'text\')"]');
                const rawTab = document.querySelector('[onclick="switchView(\'raw\')"]');

                // 默认隐藏所有标签页
                htmlTab.style.display = 'none';
                textTab.style.display = 'none';
                rawTab.style.display = 'none';
                
                // 记录第一个有内容的视图类型
                let firstAvailableView = null;

                // HTML 视图
                if (parsedEmail.html && parsedEmail.html.trim()) {
                    htmlTab.style.display = 'inline-block';
                    if (!firstAvailableView) firstAvailableView = 'html';
                    
                    const iframe = document.createElement('iframe');
                    const htmlView = document.getElementById('htmlView');
                    htmlView.innerHTML = '';
                    htmlView.appendChild(iframe);
                    
                    const doc = iframe.contentDocument || iframe.contentWindow.document;
                    doc.open();
                    doc.write(`
                        <!DOCTYPE html>
                        <html>
                        <head>
                            <meta charset="utf-8">
                            <base target="_blank">
                            <style>
                                body {
                                    font-family: Arial, sans-serif;
                                    margin: 0;
                                    padding: 15px;
                                    line-height: 1.6;
                                }
                                img { max-width: 100%; height: auto; }
                            </style>
                        </head>
                        <body>${parsedEmail.html}</body>
                        </html>
                    `);
                    doc.close();

                    iframe.onload = () => {
                        iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
                    };
                }

                // 纯文本视图
                if (parsedEmail.text && parsedEmail.text.trim()) {
                    textTab.style.display = 'inline-block';
                    if (!firstAvailableView) firstAvailableView = 'text';
                    const textView = document.getElementById('textView');
                    textView.innerHTML = `<pre style="white-space: pre-wrap; word-wrap: break-word;">${parsedEmail.text}</pre>`;
                }

                // 原始内容视图
                if (parsedEmail.raw && parsedEmail.raw.trim()) {
                    rawTab.style.display = 'inline-block';
                    if (!firstAvailableView) firstAvailableView = 'raw';
                    const rawView = document.getElementById('rawView');
                    rawView.innerHTML = `<pre style="white-space: pre-wrap; word-wrap: break-word;">${parsedEmail.raw}</pre>`;
                }

                container.style.display = 'block';
                
                // 选择第一个有内容的视图
                if (firstAvailableView) {
                    switchView(firstAvailableView);
                }

                // 显示标签页按钮容器
                document.querySelector('.tab-buttons').style.display = 'block';
            } catch (error) {
                console.error('显示邮件失败:', error);
                alert('显示邮件时发生错误');
            }
        }

        function updateEmailViews(parsedEmail) {
            const htmlView = document.getElementById('htmlView');
            if (parsedEmail.html) {
                const iframe = document.createElement('iframe');
                htmlView.innerHTML = '';
                htmlView.appendChild(iframe);
                
                const doc = iframe.contentDocument || iframe.contentWindow.document;
                doc.open();
                
                let htmlContent = parsedEmail.html;
                
                if (htmlContent.includes('=3D')) {
                    htmlContent = htmlContent.replace(/=3D/g, '=');
                }
                
                if (htmlContent.includes('=')) {
                    htmlContent = htmlContent
                        .replace(/=\r\n/g, '')
                        .replace(/=([0-9A-F]{2})/gi, (_, p1) => 
                            String.fromCharCode(parseInt(p1, 16)));
                }

                doc.write(`
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <meta charset="utf-8">
                        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                        <base target="_blank">
                        <style>
                            body {
                                font-family: Arial, sans-serif;
                                margin: 0;
                                padding: 15px;
                                line-height: 1.6;
                            }
                            img {
                                max-width: 100%;
                                height: auto;
                            }
                            pre {
                                white-space: pre-wrap;
                                word-wrap: break-word;
                                background: #f5f5f5;
                                padding: 15px;
                                border-radius: 5px;
                            }
                        </style>
                    </head>
                    <body>
                        ${htmlContent}
                    </body>
                    </html>
                `);
                doc.close();

                iframe.onload = () => {
                    iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
                    const images = iframe.contentWindow.document.getElementsByTagName('img');
                    for (let img of images) {
                        img.onerror = function() {
                            this.style.display = 'none';
                        };
                    }
                };
            } else {
                htmlView.innerHTML = '<p>无HTML内容</p>';
            }

            const textContent = parsedEmail.text || '';
            document.getElementById('textView').innerHTML = 
                `<pre style="white-space: pre-wrap; word-wrap: break-word;">${escapeHtml(textContent)}</pre>`;

            document.getElementById('rawView').innerHTML = 
                `<pre style="white-space: pre-wrap; word-wrap: break-word;">${escapeHtml(parsedEmail.raw || '')}</pre>`;
        }

        function updateAttachments(parsedEmail, container) {
            const existingAttachments = container.querySelector('.email-attachments');
            if (existingAttachments) {
                existingAttachments.remove();
            }
            
            if (parsedEmail.attachments && parsedEmail.attachments.length > 0) {
                const attachmentsDiv = document.createElement('div');
                attachmentsDiv.className = 'email-attachments';
                attachmentsDiv.innerHTML = '<h3>附件:</h3>' + 
                    parsedEmail.attachments.map(att => 
                        `<div class="attachment-item">
                            ${att.filename} (${att.contentType}, ${formatSize(att.size)})
                        </div>`
                    ).join('');
                container.appendChild(attachmentsDiv);
            }
        }

        function switchView(viewType) {
            // 移除所有标签页的激活状态
            document.querySelectorAll('.tab-button').forEach(btn => {
                if (btn.style.display !== 'none') {  // 只处理显示的标签页
                    btn.classList.remove('active');
                }
            });
            
            // 激活选中的标签页
            const activeBtn = document.querySelector(`[onclick="switchView('${viewType}')"]`);
            if (activeBtn && activeBtn.style.display !== 'none') {
                activeBtn.classList.add('active');
            }

            // 隐藏所有内容视图
            document.querySelectorAll('.content-view').forEach(view => {
                view.style.display = 'none';
            });
            
            // 显示选中的内容视图
            const activeView = document.getElementById(`${viewType}View`);
            if (activeView) {
                activeView.style.display = 'block';
            }
        }

        function updateLastUpdateTime() {
            const lastUpdateDiv = document.getElementById('lastUpdate');
            if (lastUpdateTime) {
                const now = new Date();
                const diff = now - lastUpdateTime;
                let timeText;
                
                if (diff < 60000) { // 小于1分钟
                    timeText = '刚刚';
                } else if (diff < 3600000) { // 小于1小时
                    const minutes = Math.floor(diff / 60000);
                    timeText = `${minutes}分钟前`;
                } else if (diff < 86400000) { // 小于24小时
                    const hours = Math.floor(diff / 3600000);
                    timeText = `${hours}小时前`;
                } else {
                    timeText = lastUpdateTime.toLocaleString();
                }
                
                lastUpdateDiv.textContent = `更新于: ${timeText}`;
            } else {
                lastUpdateDiv.textContent = '更新于: -';
            }
        }

        function generateRandomString(length = 8) {
            const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
            let result = '';
            for (let i = 0; i < length; i++) {
                result += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            return result;
        }

        function generateRandomEmail() {
            const randomName = generateRandomString();
            const email = `${randomName}@${DOMAIN}`;
            document.getElementById('emailInput').value = email;
            resetEmailDisplay();
            startChecking();
            return email;
        }
        
        function updateStatus(text) {
            const timeInHighFreq = highFrequencyDuration - (Date.now() - pageLoadTime);
            let statusText = text;
            
            if (timeInHighFreq > 0 && checkInterval) {
                // 计算剩余时间
                const remainingSeconds = Math.max(0, Math.floor((highFrequencyInterval - (Date.now() % highFrequencyInterval)) / 1000));
                const remainingMinutes = Math.ceil(timeInHighFreq / 60000);
                statusText += `（${remainingSeconds}秒后自动收信）`;
                
                // 每秒更新倒计时
                if (!window.countdownInterval) {
                    window.countdownInterval = setInterval(() => {
                        if (checkInterval) { // 只在监控开启时更新
                            const newRemainingSeconds = Math.max(0, Math.floor((highFrequencyInterval - (Date.now() % highFrequencyInterval)) / 1000));
                            document.getElementById('status').textContent = '状态: ' + text + 
                                `（${newRemainingSeconds}秒后自动收信）`;
                        }
                    }, 1000);
                }
            } else if (checkInterval) {
                const remainingSeconds = Math.max(0, Math.floor((lowFrequencyInterval - (Date.now() % lowFrequencyInterval)) / 1000));
                statusText += ` (${remainingSeconds}秒后自动收信)`;
            }
            
            document.getElementById('status').textContent = '状态: ' + statusText;
        }
        
        function checkEmail(isFirstCheck = false) {
            const email = document.getElementById('emailInput').value;
            if (!email) return;
            
            if (!validateEmail(email)) {
                updateStatus('邮箱地址格式错误');
                return;
            }
            
            currentEmail = email;
            updateStatus('正在检查邮件...');
            console.log('检查邮件:', {
                isFirstCheck,
                lastCheckTimestamp,
                email
            });
            
            const url = (!isFirstCheck && lastCheckTimestamp) ? 
                `/check/${email}?since=${lastCheckTimestamp}` : 
                `/check/${email}`;
            
            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('接口调用失败');  // 统一的错误信息
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('收到响应:', data);
                    
                    if (data.content) {
                        displayEmail(data);
                        lastUpdateTime = new Date();
                        updateLastUpdateTime();
                        updateStatus('收取邮件');
                        lastCheckTimestamp = data.timestamp;
                    } else {
                        updateStatus('未收到新邮件');
                        if (isFirstCheck) {
                            resetEmailDisplay();
                        }
                    }
                })
                .catch(err => {
                    console.error('检查失败:', err);  // 在控制台保留详细错误信息
                    updateStatus('接口调用失败');  // 在界面上只显示简单的错误提示
                    resetEmailDisplay();
                });
        }
        
        function checkOnce() {
            const email = document.getElementById('emailInput').value;
            if (!email) {
                alert('请输入邮箱地址');
                return;
            }
            if (!validateEmail(email)) {
                alert(`邮箱地址必须以 @${DOMAIN} 结尾`);
                return;
            }
            checkEmail(true);
        }
        
        function startChecking() {
            const email = document.getElementById('emailInput').value;
            if (!email) {
                alert('请输入邮箱地址');
                return;
            }
            if (!validateEmail(email)) {
                alert(`邮箱地址必须以 @${DOMAIN} 结尾`);
                return;
            }
            
            stopChecking();
            saveEmailToLocalStorage(email);
            
            // 立即执行第一次检查
            checkEmail(true);
            
            // 设置高频率检查定时器
            const startTime = Date.now();
            checkInterval = setInterval(() => {
                const currentTime = Date.now();
                if (currentTime - startTime < highFrequencyDuration) {
                    // 在高频率期间内
                    checkEmail(false);
                } else {
                    // 切换到低频率检查
                    clearInterval(checkInterval);
                    checkInterval = setInterval(() => checkEmail(false), lowFrequencyInterval);
                    console.log('切换到低频率检查');
                    updateStatus('自动监控中');
                }
            }, highFrequencyInterval);
            
            updateStatus('自动监控中');
            
            const button = document.getElementById('toggleMonitor');
            button.innerHTML = '❚❚';
            button.classList.remove('button-primary');
            button.classList.add('button-danger');
        }
        
        function stopChecking() {
            if (checkInterval) {
                clearInterval(checkInterval);
                checkInterval = null;
                if (window.countdownInterval) {
                    clearInterval(window.countdownInterval);
                    window.countdownInterval = null;
                }
                updateStatus('已停止监控');
                const button = document.getElementById('toggleMonitor');
                button.innerHTML = '▶';
                button.classList.remove('button-danger');
                button.classList.add('button-primary');
            }
        }

        function toggleMonitoring() {
            const button = document.getElementById('toggleMonitor');
            if (checkInterval) {
                stopChecking();
                button.innerHTML = '▶';
                button.classList.remove('monitoring');
                button.classList.remove('button-danger');
                button.classList.add('button-primary');
            } else {
                startChecking();
                button.innerHTML = '❚❚';
                button.classList.remove('button-primary');
                button.classList.add('button-danger');
            }
        }

        document.getElementById('sendTestEmail').addEventListener('click', async () => {
            const button = document.getElementById('sendTestEmail');
            const result = document.getElementById('testEmailResult');
            const email = document.getElementById('emailInput').value;
            
            if (!email) {
                result.textContent = '错误: 请先输入或生成一个邮箱地址';
                result.className = 'test-email-result error';
                return;
            }
            
            if (!validateEmail(email)) {
                result.textContent = `错误: 邮箱地址必须以 @${DOMAIN} 结尾`;
                result.className = 'test-email-result error';
                return;
            }
            
            button.disabled = true;
            result.textContent = '正在发送...';
            result.className = 'test-email-result';
            
            try {
                const response = await fetch(`/send-test-email?email=${encodeURIComponent(email)}`, {
                    method: 'POST'
                });
                const data = await response.json();
                
                if (response.ok) {
                    result.textContent = `测试邮件已发送到 ${email}`;
                    result.className = 'test-email-result success';
                } else {
                    result.textContent = '发送失败: ' + data.error;
                    result.className = 'test-email-result error';
                }
            } catch (error) {
                result.textContent = '发送失败: ' + error.message;
                result.className = 'test-email-result error';
            }
            
            button.disabled = false;
        });

        function formatSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
            if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
            return (bytes / (1024 * 1024 * 1024)).toFixed(1) + ' GB';
        }

        function saveEmailToLocalStorage(email) {
            localStorage.setItem('lastUsedEmail', email);
        }

        function getEmailFromLocalStorage() {
            return localStorage.getItem('lastUsedEmail');
        }

        document.getElementById('emailInput').addEventListener('input', function() {
            const email = this.value;
            if (email && !validateEmail(email)) {
                // 如果输入的邮箱不符合要求，自动补充或修正域名
                if (email.includes('@')) {
                    this.value = email.split('@')[0] + '@' + DOMAIN;
                } else {
                    this.value = email + '@' + DOMAIN;
                }
            }
            resetEmailDisplay();
        });

        function resetEmailDisplay() {
            const container = document.getElementById('emailContainer');
            const email = document.getElementById('emailInput').value;
            
            // 如果邮箱为空，完全隐藏邮件容器
            if (!email) {
                container.style.display = 'none';
                return;
            }
            
            container.style.display = 'block';
            
            // 重置邮件头信息
            document.getElementById('emailSubject').textContent = '主题: 暂无邮件';
            document.getElementById('emailFrom').textContent = '发件人: ';
            document.getElementById('emailTo').textContent = '收件人: ';
            document.getElementById('emailDate').textContent = '时间: ';
            
            // 隐藏所有标签页按钮和内容
            document.querySelectorAll('.tab-button').forEach(btn => {
                btn.style.display = 'none';
            });
            
            // 隐藏标签页按钮容器
            document.querySelector('.tab-buttons').style.display = 'none';
            
            // 显示提示信息
            const noMailMessage = `
                <div style="
                    text-align: center;
                    padding: 40px;
                    color: #666;
                    font-size: 16px;
                ">
                    暂无邮件，请等待接收...
                </div>
            `;
            
            // 显示提示信息，清空其他视图
            document.getElementById('htmlView').innerHTML = noMailMessage;
            document.getElementById('textView').innerHTML = '';
            document.getElementById('rawView').innerHTML = '';
            
            // 确保所有视图都��见（因为没有标签页切换）
            document.querySelectorAll('.content-view').forEach(view => {
                view.style.display = view.id === 'htmlView' ? 'block' : 'none';
            });
        }

        // 添加邮箱验证函数
        function validateEmail(email) {
            const expectedDomain = DOMAIN;
            const emailRegex = new RegExp(`^[a-zA-Z0-9._%+-]+@${expectedDomain}$`);
            return emailRegex.test(email);
        }

        // 定期更新时间显示
        setInterval(updateLastUpdateTime, 60000); // 每分钟更新一次显示

        // 添加HTML转义函数
        function escapeHtml(text) {
            if (!text) return '';
            return text
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }
    </script>
</body>
</html> 